package com.jhc.common.core.config;

import com.github.pagehelper.PageInfo;
import com.jhc.common.core.annotation.Page;
import com.jhc.api.constant.HttpStatus;
import com.jhc.common.core.utils.PageUtils;
import com.jhc.common.core.web.page.TableDataInfo;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

@RestControllerAdvice
public class PageRespAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getMethodAnnotation(Page.class) != null;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        PageUtils.clearPage();
        if (body instanceof List) {
            List list = (List) body;
            TableDataInfo rspData = new TableDataInfo();
            rspData.setCode(HttpStatus.SUCCESS);
            rspData.setRows(list);
            rspData.setMsg("查询成功");
            rspData.setTotal(new PageInfo(list).getTotal());
            return rspData;
        }
        return body;
    }
}
